<template>
  <div v-loading="loading" class="add_brand" element-loading-text="加载中...">
    <div class="header">
      <h4 class="title"> {{ route.name === 'addBrand' ? '添加品牌' : '修改品牌' }} </h4>
      <div class="btn_group">
        <HPlainButton @click="submitForm(ruleFormRef)">保存</HPlainButton>
        <HButton @click="cancelSave">取消</HButton>
      </div>
    </div>

    <div class="body">
      <div class="brand_info">
        <div class="title">品牌信息</div>
        <div class="form">
          <el-form
            ref="ruleFormRef"
            label-width="70"
            :rules="rules"
            :model="ruleForm"
            :inline="true"
            inline-message
          >
            <div class="form_content">
              <el-form-item label="品牌名称" prop="name" style="margin: 0">
                <el-input
                  v-model.trim="ruleForm.name"
                  clearable
                  :title="ruleForm.name"
                  placeholder="请输入品牌名称"
                />
              </el-form-item>
              <el-form-item label="客户名称">
                <el-input
                  v-model.trim="input1"
                  clearable
                  :title="input1"
                  placeholder="请输入客户名称"
                />
              </el-form-item>
              <el-form-item label="品牌编号" prop="code">
                <el-input
                  v-model.trim="ruleForm.code"
                  clearable
                  :title="ruleForm.code"
                  placeholder="不填写则系统生成"
                />
              </el-form-item>
              <el-form-item label="品牌电话" prop="phone" style="margin: 0">
                <el-input
                  v-model.trim="ruleForm.phone"
                  clearable
                  placeholder="请输入品牌电话"
                  maxlength="20"
                  @keyup="() => (ruleForm.phone = ruleForm.phone.replace(/[^\d]/g, ''))"
                />
              </el-form-item>
              <el-form-item label="公司地址" class="el-item">
                <SingleAddress :address="addrs" @change="handleAddressUpdate" />
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input v-model.trim="input2" clearable :title="input2" placeholder="详细地址" />
              </el-form-item>
            </div>

            <div class="img_list">
              <!--品牌标志-->
              <el-form-item label="品牌标志">
                <el-upload
                  v-if="!imgUrl1"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="getUrl1"
                  class="brand-logo"
                >
                  <el-icon :size="24" color="#007cff">
                    <UploadFilled />
                  </el-icon>
                </el-upload>
                <h-image
                  v-else
                  :padding="2"
                  :src="imgUrl1"
                  :width="80"
                  :height="50"
                  @del="onDelBrandLogo"
                >
                </h-image>
              </el-form-item>

              <!--公众号-->
              <!-- <el-form-item label="公众号">
                <h-image
                  :src="imgUrl2 || defaultUploadImg"
                  @del="onDelPublicNumberImg"
                  fit="contain"
                >
                  <el-upload
                    v-if="!imgUrl2"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="getUrl2"
                  >
                    <i class="iconfont icon-img-upload"></i>
                  </el-upload>
                </h-image>
              </el-form-item> -->
            </div>
          </el-form>
        </div>
      </div>
      <div class="param_info">
        <div class="title">
          <div class="content">
            <div class="text">参数信息</div>
            <div class="switch_container">
              <el-switch
                v-model="paraShow"
                class="switch-item"
                @change="onCustomParamSwitchChange"
              />
              <span v-show="paraShow" style="color: #333">启用</span>
              <span v-show="!paraShow" style="color: #333">禁用</span>
            </div>
          </div>
          <div class="tip">找不到参数？试试自定义参数</div>
        </div>
        <div v-show="paraShow" class="form_container">
          <div class="titles">
            <div class="serial_number">序号</div>
            <div class="param_name">参数名称</div>
            <div class="param_content">参数内容</div>
            <div class="operate">操作</div>
          </div>
          <div class="line"></div>
          <div class="form">
            <el-form
              v-for="(item, index) in items"
              ref="ruleFormRef2"
              :key="index"
              :rules="rules"
              :model="item"
              inline-message
            >
              <el-form-item class="serial_number">
                <div>{{ index + 1 }}</div>
              </el-form-item>
              <el-form-item
                class="param_name"
                :rules="[
                  { required: true, message: '请输入参数名称', trigger: ['change', 'blur'] },
                ]"
                prop="name"
              >
                <el-input
                  v-model.trim="item.name"
                  placeholder="请输入参数名称"
                  class="para-name"
                  clearable
                />
              </el-form-item>
              <el-form-item
                class="param_content"
                :rules="[
                  { required: true, message: '请输入参数名称', trigger: ['change', 'blur'] },
                ]"
                prop="val"
              >
                <el-input
                  v-model.trim="item.val"
                  placeholder="请输入参数内容"
                  class="para-val"
                  clearable
                />
              </el-form-item>
              <el-form-item class="operate">
                <el-space :size="0" :spacer="spacer">
                  <HLink v-if="items.length > 1" type="error" @click="handleDele(index, item)"
                    >删除</HLink
                  >
                  <h-link v-if="index === 0 && items.length < 10" @click="addText">添加</h-link>
                </el-space>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="brand_introduce">
        <div class="title">品牌介绍</div>
        <div class="form">
          <Editor ref="editorRef" :value="ediorData.content" />
        </div>
      </div>
    </div>
    <el-dialog v-model="imgPreviewModalVisible" title="图片预览" @close="onCloseImgPreviewModal">
      <div style="display: flex; justify-content: center">
        <el-image :src="imgPreviewUrl" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { saveBrand } from '@/api/brand'
  import { ref, reactive, onMounted, h, watch } from 'vue'
  import type { UploadProps, FormInstance, UploadFile } from 'element-plus'
  import { ElDivider, ElMessage } from 'element-plus'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { getBrandDetail } from '@/api/brand'
  import { proAnnexUpload } from '@/api/upload'
  import { useRoute, useRouter } from 'vue-router'
  import { verifyTelephone } from '@/utils/validate'
  import defaultUploadImg from '@/assets/image/avatar_upload_default.png'
  import Editor from '@/components/business/editor/Editor.vue'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.good.brandForm,
  })

  // 编辑器组件实例
  const editorRef = ref<InstanceType<typeof Editor> | null>(null)

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const onCustomParamSwitchChange = () => {
    if (items.value.length <= 0 && paraShow.value) {
      items.value.push({
        name: '',
        val: '',
      })
    }
  }

  // 标签状态管理
  const TagsViewStore = useTagsViewStore()
  const route = useRoute()
  const router = useRouter()
  const SettingStore = useSettingStore()
  const loading = ref(false)
  const addrs = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  }) // 公司地址
  const addrTitle = ref('')
  const input1 = ref('') // 客户名称
  const input2 = ref('') // 详细地址
  const status = ref() // 品牌状态
  const paraShow = ref(false) // 是否启用参数
  const showCode = ref(false)

  // 品牌介绍内容 HTML
  const ediorData = ref({ content: '', type: 'goods' })

  // 参数数量
  const items = ref([
    {
      name: '',
      val: '',
    },
  ])

  const itemIds = ref([]) // 删除品牌参数ID集合

  // 图片地址 1-品牌标志 2-公众号
  const imgUrl1 = ref('')
  const imgUrl2 = ref('')

  const mark = ref()
  const publicNo = ref()

  // 表单数据
  const ruleForm = reactive({
    name: '', // 品牌名称
    code: '', // 品牌名称,
    phone: '', // 品牌电话
  })

  // 表单元素
  const ruleFormRef = ref<FormInstance>()
  const ruleFormRef2 = ref<Array<FormInstance>>([])

  // 验证规则
  const rules = reactive({
    name: [
      { required: true, message: '请输入品牌名称', trigger: ['blur', 'change'] },
      { max: 20, message: '最多20个字符', trigger: ['blur', 'change'] },
    ],
    code: [{ required: false, message: '请输入品牌编号', trigger: ['blur', 'change'] }],
    phone: [
      { required: false, message: '请输入正确的品牌电话', trigger: ['blur', 'change'] },
      {
        pattern: verifyTelephone().pattern,
        message: '电话号码格式不正确',
        trigger: ['blur', 'change'],
      },
    ],
  })

  // 删除参数内容
  const handleDele = (i, obj) => {
    items.value.splice(i, 1)
    if (obj.id) {
      itemIds.value.push(obj.id)
    }
  }

  // 新增参数内容
  const addText = () => {
    items.value.push({
      name: '',
      val: '',
    })
  }

  // 图片预览弹窗状态
  const imgPreviewModalVisible = ref(false)

  // 图片预览地址
  const imgPreviewUrl = ref('')

  // 图片预览弹窗关闭事件
  const onCloseImgPreviewModal = () => {
    imgPreviewModalVisible.value = false
    imgPreviewUrl.value = ''
  }

  // 品牌标志上传事件
  const getUrl1: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    imgUrl1.value = window.URL.createObjectURL(uploadFile.raw)
    mark.value = uploadFile.raw
  }

  // 删除品牌标志图片
  const onDelBrandLogo = () => {
    imgUrl1.value = ''
    mark.value = null
  }

  // 预览品牌标志
  const onPreviewBrandLogo = () => {
    imgPreviewModalVisible.value = true
    imgPreviewUrl.value = imgUrl1.value
  }

  // 公众号图片上传事件
  const getUrl2: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    imgUrl2.value = window.URL.createObjectURL(uploadFile.raw)
    publicNo.value = uploadFile.raw
  }

  // 删除品牌标志图片
  const onDelPublicNumberImg = () => {
    imgUrl2.value = ''
    publicNo.value = null
  }

  // 预览品牌标志
  const onPreviewPublicNumberImg = () => {
    imgPreviewModalVisible.value = true
    imgPreviewUrl.value = imgUrl2.value
  }

  // 地址
  const address = ref({
    province: '',
    area: '',
    city: '',
    town: '',
  })

  // 地址更新事件
  const handleAddressUpdate = (addr: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    Object.assign(address.value, { ...addr })
  }

  // 保存数据
  const submitForm = (formEl: FormInstance | undefined) => {
    let paramInfoValidateResult = true
    if (paraShow.value) {
      ruleFormRef2.value.forEach((form) => {
        try {
          form.validate()
        } catch (error) {
          paramInfoValidateResult = false
          return
        }
      })
    }

    if (!paramInfoValidateResult) {
      return
    }

    const tmp = items.value.map((item) => {
      return {
        name: item.name,
        val: item.val,
      }
    })

    // 新增的品牌数据
    const data = {
      name: ruleForm.name, // 品牌名称
      status: false, // 品牌状态：false-启用，true-禁用
      address: input2.value, // 公司地址-详细地址
      area: address.value.area, // 公司地址-县/区
      brandParamIds: itemIds.value, // 删除品牌参数ID集合
      brandParamVos: tmp, // 品牌参数
      city: address.value.city, // 公司地址-市
      code: ruleForm.code, // 品牌编号
      company: input1.value, // 客户名称
      describe: '', // 品牌介绍
      mark: '', // 品牌标志路径
      province: address.value.province, // 公司地址-省
      publicNo: '', // 公众号
      telephone: ruleForm.phone, // 品牌电话
      town: address.value.town, // 公司地址-镇
    }

    // 修改的品牌数据
    const data2 = {
      id: route.params.id, // 品牌id
      name: ruleForm.name, // 品牌名称
      status: status.value, // 品牌状态：false-启用，true-禁用
      address: input2.value, // 公司地址-详细地址
      area: address.value.area, // 公司地址-县/区
      brandParamIds: itemIds.value, // 删除品牌参数ID集合
      brandParamVos: items.value, // 品牌参数
      city: address.value.city, // 公司地址-市
      code: ruleForm.code, // 品牌编号
      company: input1.value, // 客户名称
      describe: '', // 品牌介绍
      mark: '', // 品牌标志路径
      province: address.value.province, // 公司地址-省
      publicNo: '', // 公众号
      telephone: ruleForm.phone, // 品牌电话
      town: address.value.town, // 公司地址-镇
    }

    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        loading.value = true

        if (editorRef.value) {
          const files = editorRef.value.getUploadFiles().map((file) => file.file)
          const fileTempUrl = editorRef.value.getUploadFiles().map((file) => file.tempUrl)
          if (files.length > 0) {
            const res = await proAnnexUpload(files)
            res.data.data.rows.forEach((fileUrl: string, fileUrlIndex: number) => {
              editorRef.value.convertTempPathToServerPath(fileTempUrl[fileUrlIndex], fileUrl)
            })
          }
        }

        if (imgUrl1.value) {
          const files = []
          files.push(mark.value)
          if (files.length != 0) {
            const res = await proAnnexUpload(files)
            data.mark = res.data.data.rows[0]
            data2.mark = res.data.data.rows[0]
            imgUrl1.value = res.data.data.rows[0]
          }
        }
        if (imgUrl2.value) {
          const files = []
          files.push(publicNo.value)
          if (files.length != 0) {
            const res = await proAnnexUpload(files)
            data.publicNo = res.data.data.rows[0]
            data2.publicNo = res.data.data.rows[0]
            imgUrl2.value = res.data.data.rows[0]
          }
        }
        if (route.params.id != undefined) {
          data2.describe = editorRef.value ? await editorRef.value.getEditorValue() : ''
          // 修改品牌
          const res = await saveBrand(data2)
          if (res.data.success == true) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
            SettingStore.setReload()
            TagsViewStore.delView(route.path) // 关闭当前页面
            router.push('/busic/base/proset?active=brandSet')
            loading.value = false
          } else {
            ElMessage({
              message: res.data.message,
              type: 'warning',
              duration: 5000,
              plain: true,
              showClose: true,
            })
            loading.value = false
            return
          }
        } else {
          data.describe = editorRef.value ? await editorRef.value.getEditorValue() : ''
          // 新增品牌
          const res = await saveBrand(data)
          if (res.data.success == true) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
            SettingStore.setReload()
            TagsViewStore.delView(route.path) // 关闭当前页面
            router.push('/busic/base/proset?active=brandSet')
            loading.value = false
          } else {
            ElMessage({
              message: res.data.message,
              type: 'warning',
              duration: 5000,
              plain: true,
              showClose: true,
            })
            loading.value = false
            return
          }
        }
      } else {
        return
      }
    })
  }

  // 取消保存
  const cancelSave = () => {
    TagsViewStore.delView(route.path) // 关闭当前页面
    router.go(-1) // 返回列表页面
  }

  watch(
    () => TagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path) && editorRef.value) {
        editorRef.value.destoryEditor()
      }
    },
  )

  onMounted(async () => {
    // 判断是  新增/修改  id 有值为修改品牌
    if (route.params.id != undefined) {
      loading.value = true
      await getBrandDetail(route.params.id).then((res) => {
        rules.code[0].required = true
        const row = res.data.data.row
        ruleForm.name = row.name
        ruleForm.code = row.code
        showCode.value = true
        status.value = row.status
        input1.value = row.company
        ruleForm.phone = row.telephone
        addrs.value = {
          province: row.province,
          city: row.city,
          area: row.area,
          town: row.town,
        }
        addrTitle.value = row.province + '-' + row.city + '-' + row.area + '-' + row.town
        input2.value = row.address
        imgUrl1.value = row.mark
        imgUrl2.value = row.publicNo
        items.value = row.brandParamVos
        ediorData.value = { content: row.describe, type: 'goods' }
        if (row.brandParamVos.length != 0) {
          paraShow.value = true
        }
      })
      loading.value = false
      if (editorRef.value) {
        editorRef.value.mountEditor()
      }
    }
  })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
